﻿using System;
using System.IO;
using System.Text.Json;
using IntegratedMeasuring.Storage;
using IntegratedMeasuring.ViewModels.Scheme;

namespace IntegratedMeasuring.ViewModels.Entity;

public static class GV
{
    // 仪器类型
    public static GC.InstrumentModelType InstrumentModel { get; set; } = GC.InstrumentModelType.TH2837AX;  
    // 串口号
    public static string SerialPortNum { get; set; } = string.Empty;
    
    // 波特率
    public static int BaudRate { get; set; } = 9600;
    
    // 服务器地址
    public static string ServerAddress { get; set; } = string.Empty;
    
    // 令牌
    public static string Token { get; set; } = string.Empty;
    
    // 设备编号
    public static string DeviceNumber { get; set; } = string.Empty;
    
    // 产线编号
    public static string ProductionLineNumber { get; set; } = string.Empty;
    
    // 条码设置
    public static bool EnableBarcodeScan { get; set; } = false;
    public static bool EnableBarcodeValidation { get; set; } = false;
    public static string BarcodePrefix { get; set; } = string.Empty;
    public static string BarcodeSuffix { get; set; } = string.Empty;
    public static int BarcodeLength { get; set; } = 0;
    public static int RetestCount { get; set; } = 0;
    public static int TestedMultipleTimes { get; set; } = 0;  // 已重测的次数
    
    public static GC.DuplicateCodeHandlingType DuplicateCodeHandling { get; set; } = GC.DuplicateCodeHandlingType.SaveAsNew;
    
    // 数据设置
    public static string FilePath { get; set; } = "D:\\ProgramData\\IntegratedMeasuring";
    public static int AutoSaveInterval { get; set; } = 60;
    public static bool EnableAutoBackup { get; set; } = true;
    public static string BackupPath { get; set; } = "D:\\Backup";
    
    // 用户设置
    public static string Theme { get; set; } = "浅色主题";
    public static string Language { get; set; } = "简体中文";
    public static bool EnableAutoLogin { get; set; } = false;
    
    public static bool IsMounted { get; set; } = false;  // 仪器是否已挂载并初始化完成
    public static bool IsSpotMode { get; set; } = false;

    public static long CurrentOrderId { get; set; } = 0;
    public static string CurrentOrders { get; set; } = string.Empty;
    public static string CurrentTestConditions { get; set; } = string.Empty;

    public static ProductInfo? LastTestProductInfo = null;
    
    public static void LoadGVFromLocalFile()
    {
        string filePath = Path.Combine(AppContext.BaseDirectory, "dep\\conf\\runtime.data");
        if (!File.Exists(filePath))
            return;

        try
        {
            string json = File.ReadAllText(filePath);
            using var doc = JsonDocument.Parse(json);
            var root = doc.RootElement;

            // 逐个字段赋值
            if (root.TryGetProperty("InstrumentModel", out var instrumentModel))
                InstrumentModel = (GC.InstrumentModelType)instrumentModel.GetInt32();
            if (root.TryGetProperty("SerialPortNum", out var serialPortNum))
                SerialPortNum = serialPortNum.GetString() ?? string.Empty;
            if (root.TryGetProperty("BaudRate", out var baudRate))
                BaudRate = baudRate.GetInt32();
            if (root.TryGetProperty("ServerAddress", out var serverAddress))
                ServerAddress = serverAddress.GetString() ?? string.Empty;
            if (root.TryGetProperty("Token", out var token))
                Token = token.GetString() ?? string.Empty;
            if (root.TryGetProperty("DeviceNumber", out var deviceNumber))
                DeviceNumber = deviceNumber.GetString() ?? string.Empty;
            if (root.TryGetProperty("ProductionLineNumber", out var productionLineNumber))
                ProductionLineNumber = productionLineNumber.GetString() ?? string.Empty;
            if (root.TryGetProperty("EnableBarcodeScan", out var enableBarcodeScan))
                EnableBarcodeScan = enableBarcodeScan.GetBoolean();
            if (root.TryGetProperty("EnableBarcodeValidation", out var enableBarcodeValidation))
                EnableBarcodeValidation = enableBarcodeValidation.GetBoolean();
            if (root.TryGetProperty("BarcodePrefix", out var barcodePrefix))
                BarcodePrefix = barcodePrefix.GetString() ?? string.Empty;
            if (root.TryGetProperty("BarcodeSuffix", out var barcodeSuffix))
                BarcodeSuffix = barcodeSuffix.GetString() ?? string.Empty;
            if (root.TryGetProperty("BarcodeLength", out var barcodeLength))
                BarcodeLength = barcodeLength.GetInt32();
            if (root.TryGetProperty("RetestCount", out var retestCount))
                RetestCount = retestCount.GetInt32();
            if (root.TryGetProperty("DuplicateCodeHandling", out var duplicateCodeHandling))
                DuplicateCodeHandling = (GC.DuplicateCodeHandlingType)duplicateCodeHandling.GetInt32();
            if (root.TryGetProperty("FilePath", out var localfilePath))
                FilePath = localfilePath.GetString() ?? "D:\\ProgramData\\IntegratedMeasuring";
            if (root.TryGetProperty("CurrentOrders", out var crrentOrders))
                CurrentOrders = crrentOrders.GetString() ?? string.Empty;
            if (root.TryGetProperty("CurrentOrderId", out var currentOrderId))
                CurrentOrderId = currentOrderId.GetInt64();
            if (root.TryGetProperty("AutoSaveInterval", out var autoSaveInterval))
                AutoSaveInterval = autoSaveInterval.GetInt32();
            if (root.TryGetProperty("EnableAutoBackup", out var enableAutoBackup))
                EnableAutoBackup = enableAutoBackup.GetBoolean();
            if (root.TryGetProperty("BackupPath", out var backupPath))
                BackupPath = backupPath.GetString() ?? "D:\\Backup";
            if (root.TryGetProperty("Theme", out var theme))
                Theme = theme.GetString() ?? "浅色主题";
            if (root.TryGetProperty("Language", out var language))
                Language = language.GetString() ?? "简体中文";
            if (root.TryGetProperty("EnableAutoLogin", out var enableAutoLogin))
                EnableAutoLogin = enableAutoLogin.GetBoolean();
        }
        catch (Exception ex)
        {
            LogDataStorage.Instance.SaveLogRecord(new LogRecord
            {
                Level = GC.LogLevel.ERROR,
                CreateTime = DateTime.Now,
                Content = $"{ex.Message}\r\n{ex.StackTrace}",
                Title = "运行时数据加载解析失败",
            });
        }
    }

    public static void SaveGVToLocalFile()
    {
        string filePath = Path.Combine(AppContext.BaseDirectory, "dep\\conf\\runtime.data");
        
        try
        {
            var data = new
            {
                InstrumentModel = (int)InstrumentModel,
                SerialPortNum = SerialPortNum,
                BaudRate = BaudRate,
                ServerAddress = ServerAddress,
                Token = Token,
                DeviceNumber = DeviceNumber,
                ProductionLineNumber = ProductionLineNumber,
                EnableBarcodeScan = EnableBarcodeScan,
                EnableBarcodeValidation = EnableBarcodeValidation,
                BarcodePrefix = BarcodePrefix,
                BarcodeSuffix = BarcodeSuffix,
                BarcodeLength = BarcodeLength,
                RetestCount = RetestCount,
                DuplicateCodeHandling = (int)DuplicateCodeHandling,
                FilePath = FilePath,
                CurrentOrders = CurrentOrders,
                CurrentOrderId = CurrentOrderId,
                AutoSaveInterval = AutoSaveInterval,
                EnableAutoBackup = EnableAutoBackup,
                BackupPath = BackupPath,
                Theme = Theme,
                Language = Language,
                EnableAutoLogin = EnableAutoLogin
            };

            string json = JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true });
            File.WriteAllText(filePath, json);
        }
        catch (Exception ex)
        {
            // todo 记录日志
        }
    }
    
    public static InsComMeta GetInstInfo()
    {
        return GC.InstrumentModelTypeDict[(int)InstrumentModel];
    }
}

